#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc,char* argv[]){

	int fd = open("foo.txt",O_RDWR);
	struct stat* state = (struct stat*)malloc(sizeof(struct stat)); //stat结构体用于读取文件描述符所对应文件的信息
	fstat(fd,state); //读取文件信息，记录与state

	int err_code;
	
	printf("inode: %ld\n",state->st_ino);//打印inode号
	printf("nlink before rm: %ld\n",state->st_nlink);//删除前
	printf("mode : %o\n",state->st_mode);//打印文件的权限之类的信息

	//umask(0000);
	//open("foo_backup.txt",O_CREAT|O_RDWR ,0777); //注意：之前犯错了，连接的时候新文件不能存在，原文件必须存在
	err_code = link("foo.txt","foo_backup.txt");  //创建副本并连接
	printf("if link succ: %d\n",err_code);

	fstat(fd,state); //更新文件信息，记录与state

	printf("nlink before rm: %ld\n",state->st_nlink);//连接更新后  2

	unlink("foo.txt");//删除foo.txt

	fstat(fd,state); //更新文件信息，记录与state

	printf("nlink after rm: %ld\n",state->st_nlink);//删除后   1

	unlink("foo_backup.txt");//删除foo_backup.txt
	
	free(state);

	return 0;
}
